package com.originskyseed.platform.user.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.originskyseed.platform.user.model.LevelSystem;
import com.originskyseed.platform.user.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Company;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.ParameterConfigure;
import com.originskyseed.platform.user.vo.request.CompanyRequestVO;
import com.originskyseed.platform.user.vo.request.DeptRequestVO;

/**
 * 公司信息Controller类（OSI_COMPANY）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/company")
@BaseLocaleResource(localeFileName = "i18n_user")
public class CompanyController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);

	@DubboReference
	private ICompanyService companyService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IParameterConfigureService parameterConfigureService;

	@DubboReference
	private ILevelSystemService levelSystemService;

	@DubboReference
	private ILevelSystemRelDeptService levelSystemRelDeptService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/companyList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Company>> companyList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Company>> result = null;
		try {
			// 请求对象
			CompanyRequestVO requestVO = this.getParameterBean(CompanyRequestVO.class);

			// 分页查询
			BasePage<Company> page = new BasePage<Company>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.companyService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<Company>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Company>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deptList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody deptList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			DeptRequestVO requestVO = this.getParameterBean(DeptRequestVO.class);
			requestVO.setType(2);

			// 分页查询
			BasePage<Dept> page = new BasePage<Dept>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.deptService.selectListRelComByPage(requestVO.toMap(), page);

			List<ParameterConfigure> parameterConfigureList = parameterConfigureService.selectByParentCode("BUSINESS_SCOPE");
			for (Dept dept : page.getResults()) {

				// 查询下级部门
				List<Dept> deptList = this.deptService.selectByParentCode(dept.getCode());
				dept.setSonDeptName("");
				if (deptList != null) {
					for (Dept dept1 : deptList) {
						dept1.setUserNum(0);
						dept1.setSonDeptName("");
						dept.setSonDeptName(dept.getSonDeptName() + "、" + dept1.getName());
					}
					if (dept.getSonDeptName().length() > 0) {
						dept.setSonDeptName(dept.getSonDeptName().substring(1));
					}
					dept.setDeptList(deptList);
				}

				// 查询员工数量
				dept.setUserNum(selectUserNum(dept));

				// 查询业务范畴
				for (ParameterConfigure parameterConfigure : parameterConfigureList) {
					if (parameterConfigure.getCode().equals(dept.getBusinessScope())) {
						dept.setBusinessScopeName(parameterConfigure.getName());
						break;
					}
				}

				// 查询等级体系id,查询等级体系名称
			 	String systemLevelId = this.levelSystemRelDeptService.selectLevelSystemIdByDeptId(dept.getId());
				LevelSystem levelSystem = this.levelSystemService.selectByPrimaryKey(systemLevelId);
				if(levelSystem!=null){
					dept.setSystemId(levelSystem.getId());
					dept.setSystemName(levelSystem.getTitle());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/companySave.json", method = RequestMethod.POST)
	public BaseResponseBody<Company> companySave(HttpServletRequest request) {
		BaseResponseBody<Company> result = null;
		try {
			// 请求对象
			Company company = this.getParameterBean(Company.class);

			if (StringUtils.isNotBlank(company.getId())) {
				this.companyService.updateByPrimaryKey(company);
			} else {
				this.companyService.insertSelective(company);
			}
			result = new BaseResponseBody<Company>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), company);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Company>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/companyDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> companyDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.companyService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询组织架构
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deptStructure.json")
	public BaseResponseBody deptStructure(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);

			// 获取分公司部门信息
			Dept companyDept = this.deptService.selectByPrimaryKey(id);
			int companyDeptUserNum = this.userInfoService.selectUserNumByDeptId(companyDept.getId());
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", companyDept.getId());
			jsonObject.put("name", companyDept.getName());
			jsonObject.put("expand", true);

			// 查询分公司下的部门
			List<Dept> deptList = this.deptService.selectByParentCode(companyDept.getCode());
			JSONArray jsonArray = new JSONArray();
			for (Dept dept : deptList) {
				// 统计总的数量
				int deptUserNum = this.userInfoService.selectUserNumByDeptId(dept.getId());
				companyDeptUserNum += deptUserNum;

				JSONObject deptJsonObject = new JSONObject();
				deptJsonObject.put("id", dept.getId());
				deptJsonObject.put("name", dept.getName());
				deptJsonObject.put("expand", true);

				// 查询部门下的厅
				List<Dept> officeList = this.deptService.selectByParentCode(dept.getCode());
				JSONArray officeJsonArray = new JSONArray();
				for (Dept officeDept : officeList) {
					// 统计总的数量
					int officeUserNum = this.userInfoService.selectUserNumByDeptId(officeDept.getId());
					companyDeptUserNum += officeUserNum;
					deptUserNum += officeUserNum;

					JSONObject officeJsonObject = new JSONObject();
					officeJsonObject.put("id", officeDept.getId());
					officeJsonObject.put("name", officeDept.getName());
					officeJsonObject.put("expand", true);

					// 查询厅下面的小组
					List<Dept> groupList = this.deptService.selectByParentCode(officeDept.getCode());
					JSONArray groupJsonArray = new JSONArray();
					for (Dept groupDept : groupList) {
						// 统计总得数量
						int groupUserNum = this.userInfoService.selectUserNumByDeptId(groupDept.getId());
						companyDeptUserNum += groupUserNum;
						officeUserNum += groupUserNum;
						deptUserNum += groupUserNum;

						JSONObject groupJsonObject = new JSONObject();
						groupJsonObject.put("id", groupDept.getId());
						groupJsonObject.put("name", groupDept.getName());
						groupJsonObject.put("expand", true);
						groupJsonObject.put("label", groupDept.getName() + "(" + groupUserNum + ")");
						groupJsonObject.put("count", groupUserNum);
						groupJsonArray.add(groupJsonObject);
					}
					officeJsonObject.put("label", officeDept.getName() + "(" + officeUserNum + ")");
					officeJsonObject.put("count", officeUserNum);
					officeJsonObject.put("children", groupJsonArray);
					officeJsonArray.add(officeJsonObject);
				}
				deptJsonObject.put("label", dept.getName() + "(" + deptUserNum + ")");
				deptJsonObject.put("count", deptUserNum);
				deptJsonObject.put("children", officeJsonArray);
				jsonArray.add(deptJsonObject);
			}
			jsonObject.put("label", companyDept.getName() + "(" + companyDeptUserNum + ")");
			jsonObject.put("count", companyDeptUserNum);
			jsonObject.put("children", jsonArray);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonObject);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据部门id查询公司
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCompanyByDeptId.json", method = RequestMethod.POST)
	public BaseResponseBody selectCompanyByDeptId(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);

			Company company = this.companyService.selectByDeptId(id);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), company);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询分公司下员工数量
	 * 
	 * @param companyDept
	 * @return
	 * @throws Exception
	 */
	private Integer selectUserNum(Dept companyDept) throws Exception {
		int companyDeptUserNum = this.userInfoService.selectUserNumByDeptId(companyDept.getId());

		// 查询分公司下的部门
		List<Dept> deptList = this.deptService.selectByParentCode(companyDept.getCode());
		for (Dept dept : deptList) {
			// 统计总的数量
			int deptUserNum = this.userInfoService.selectUserNumByDeptId(dept.getId());
			companyDeptUserNum += deptUserNum;

			// 查询部门下的厅
			List<Dept> officeList = this.deptService.selectByParentCode(dept.getCode());
			for (Dept officeDept : officeList) {
				// 统计总的数量
				int officeUserNum = this.userInfoService.selectUserNumByDeptId(officeDept.getId());
				companyDeptUserNum += officeUserNum;

				// 查询厅下面的小组
				List<Dept> groupList = this.deptService.selectByParentCode(officeDept.getCode());
				for (Dept groupDept : groupList) {
					// 统计总得数量
					int groupUserNum = this.userInfoService.selectUserNumByDeptId(groupDept.getId());
					companyDeptUserNum += groupUserNum;
				}
			}
		}
		return companyDeptUserNum;
	}
}